package com.rmfyzxfw.caseprocess.boot.xss;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import org.springframework.context.annotation.Bean;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
 * @description:
 * @author: Lixx
 * @time: 2023/2/4 15:45
 */
/**
 * 对json格式数据做序列化和反序列化操作,防止xss攻击
 * XssFilter类
 * XssHttpServletRequestWrapper类
 * XssStringJsonDeSerializer类
 * XssStringJsonSerializer类
 * JacksonConfig类
 * 这5个类是一起的，都是用来防止xss攻击,前2个类是用来处理提交方式为x-www-form-urlencoded和form-data做特殊字符转换
 * 后面三类是对application/json提交方式做处理
 */
//@Configuration
public class JacksonConfig implements WebMvcConfigurer{

    @Bean
    public ObjectMapper xssObjectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();
        //注入自定义的序列化工具,将@RequestBody的json格式参数做转义处理
        SimpleModule simpleModule = new SimpleModule(XssStringJsonSerializer.class.getSimpleName());
        //只对入参json进行特殊字符转义
        simpleModule.addDeserializer(String.class, new XssStringJsonDeSerializer());
        //对返回给前端的json数据(特殊字符)进行转义,这里暂时注释掉,当前项目暂不需要对返回给前端的数据进行转义
        //simpleModule.addSerializer(String.class, new XssStringJsonSerializer());
        objectMapper.registerModule(simpleModule);
        return objectMapper;
    }
}
